/*
 * DocumentSerializer.java
 *
 * Created on 12 czerwiec 2007, 10:48
 */

package edu.uj.petri.document;

import edu.uj.petri.model.Model;
import edu.uj.petri.view.View;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author Piotrek
 */
public class DocumentSerializer implements DocumentSaver {
    
    private OutputStream outputStream;
    private Model model;
    private View view;
    
    /** Creates a new instance of DocumentSerializer */
    public DocumentSerializer() {
    }
    
    public void setOutputStream(OutputStream stream) {
        outputStream = new BufferedOutputStream(stream);
    }
    
    public void save(Document document) throws Exception {
        XMLEncoder encoder = null;
        
        try {
            encoder = new XMLEncoder(outputStream);
            encoder.writeObject(document.getModel());
            encoder.writeObject(document.getView());
        } finally {
            try {
                if (encoder != null)
                    encoder.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public void read(InputStream stream) throws Exception {
        XMLDecoder      decoder     = null;
        
        try {
            decoder = new XMLDecoder(new BufferedInputStream(
                    stream));
            
            model = (Model) decoder.readObject();
            view  = (View)  decoder.readObject();
            
            if (model == null || view == null)
                throw new Exception("model or view null");
            
        } finally {
            try {
                if (decoder != null)
                    decoder.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public Model getModel() {
        return model;
    }
    
    public View getView() {
        return view;
    }
    
}
